import React, { useState, useEffect } from 'react';
import './index.less';
import CabinetModel from './Model/CabinetModel';
import { Button, message } from 'antd';
import { Getstatus } from './utils';
import { RemoteOpenLock, ruchangshouquan, chuchangshouquan } from "./service"
const Cabinet = ({ data, Radiovalue, UpdateList }) => {
    /* 弹窗开关、坐标、当前 item */
    const [visible, setVisible] = useState(false);
    const [pos, setPos] = useState({ x: 0, y: 0 });
    const [curItem, setCurItem] = useState(null);
    // 弹窗状态
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 点击数据
    const [ItemData, setItemData] = useState({})
    // 弹出位子
    const [arrow, setArrow] = useState('bottom');

    /* 右键触发 */
    const handleRightClick = (e, item) => {
        e.preventDefault();
        setCurItem(item);

        const GAP = 4;
        const menuWidth = 120;
        const menuHeight = 64;

        let x = e.clientX + GAP;
        let y = e.clientY + GAP;
        let arrow;

        // 水平方向
        if (x + menuWidth > window.innerWidth) {
            x = e.clientX - menuWidth - GAP;
            arrow = 'right';
        } else {
            arrow = 'left';
        }

        // 垂直方向
        if (y + menuHeight > window.innerHeight) {
            y = e.clientY - menuHeight - GAP;
            arrow = 'top';
        } else {
            arrow = 'bottom';
        }

        setPos({ x, y });
        setArrow(arrow);          //  新增一个状态
        setVisible(true);
    };
    /* 点击页面其它地方关闭 */
    useEffect(() => {
        const close = () => setVisible(false);
        window.addEventListener('click', close);
        window.addEventListener('wheel', close);
        return () => {
            window.removeEventListener('click', close);
            window.removeEventListener('wheel', close);
        };
    }, []);

    /* 两个按钮的回调 */
    const onBtn = (type) => {
        console.log(curItem);
        setVisible(false);
        if (type == "c") {
            let data = {
                "shichang": "10",
                "zhuangtai": "0",
                "source": 1,
                "guihao": curItem.locker_number,
                "lockclass": curItem.locker_type,
                "uuid": new Date().getTime().toString(),
            }
            RemoteOpenLock(data).then(res => {
                if (res.result == 0) {
                    message.success("开锁成功")
                } else {
                    message.error("开锁失败 : " + res.msg)
                }
            }).catch(err => {
                message.error("开锁失败 : " + err.message)
            })
        }
        if (type == "A") {
            ruchangshouquan({
                "youxiaoqi": "10",
                "youxiaoqineideng": "1",
                "youxiaoqiwaideng": "0",
                "source": 1,
                "guihao": curItem.locker_number,
                "uuid": new Date().getTime().toString(),
                "lockclass": curItem.locker_type,

            }).then(res => {
                if (res.result == 0) {
                    message.success(curItem.locker_number + "入场授权成功")
                } else {
                    message.error("授权失败 : " + res.msg)
                }
            }).catch(err => {
                message.error("授权失败 : " + err.message)
            })
        }

        if (type == "B") {
            chuchangshouquan({
                "youxiaoqi": "10",
                "youxiaoqineideng": "1",
                "youxiaoqiwaideng": "0",
                "source": 1,
                "guihao": curItem.locker_number,
                "uuid": new Date().getTime().toString(),
                "lockclass": curItem.locker_type,
            }).then(res => {
                if (res.result == 0) {
                    message.success(curItem.locker_number + "离场授权成功")
                } else {
                    message.error("授权失败 : " + res.msg)
                }
            }).catch(err => {
                message.error("授权失败 : " + err.message)
            })
        }
    };

    const ClickItem = (item) => {
        console.log(item)

        setItemData(item)
        setIsModalOpen(true)
    }

    console.log("数据", data, Radiovalue)

    return (
        <div>
            <div className="cabinet " style={{ minWidth: "70vw" }}>
                {data.map((I, idx) => (
                    <div key={idx} >
                        <div style={{ margin: 5, fontWeight: 550, fontSize: 20, position: 'relative', paddingBottom: 4 }}>
                            {
                                Radiovalue == 2 ? I.area_name == "" ? "未分配管理区" : I.area_name : I.controller_name == "" ? "未配置控制器" : I.controller_name
                            }
                            <span
                                style={{
                                    position: 'absolute',
                                    left: 0,
                                    right: 0,
                                    bottom: 0,
                                    height: 1,
                                    background: '#d9d9d9',
                                    transform: 'scaleY(0.5)',   // 把 1 px 压成 0.5 px
                                    transformOrigin: 'bottom'
                                }}
                            /></div>
                        <div className="flex">

                            {
                                I.list.map((item) => {
                                    return <div
                                        key={item.id}
                                        className={Getstatus(item.usage_status).ClassName}
                                        onContextMenu={e => handleRightClick(e, item)}
                                        onClick={() => ClickItem(item)}
                                        
                                    >
                                        <div className="text f17" style={{color:"#fff"}}>{item.locker_number}</div>
                                        <div className="text">
                                            {item.locker_user_type} &nbsp;
                                            <span className="f12">{item.locker_type} </span>
                                        </div>
                                        <div className="text">{Getstatus(item.usage_status).Text}</div>
                                        <div className="text">{item.power}</div>
                                        {/* <div>{item.isline === 1 ? '在线' : <span className="Span">不在线</span>}</div> */}
                                    </div>
                                })
                            }
                        </div>
                    </div>
                ))}
            </div>

            {/* 右键小弹窗 */}
            {visible && (
                <div
                    className={`right-menu arrow-${arrow}`}   // 动态挂箭头
                    style={{ position: 'fixed', left: pos.x, top: pos.y, zIndex: 9999 }}
                    onClick={e => e.stopPropagation()} // 防止冒泡到 window 被关闭
                >
                    <div
                        className='mt10 mlr10'

                        onClick={() => onBtn('A')}
                    >
                        <Button>入场授权</Button>
                    </div>
                    <div
                        className='mt10 mlr10'
                        onClick={() => onBtn('B')}
                    >
                        <Button>离场授权</Button>

                    </div>
                    <div
                        className='mt10 mlr10'
                        onClick={() => onBtn('c')}
                    >
                        <Button>远程开锁</Button>

                    </div>
                </div>
            )}

            {isModalOpen && <CabinetModel UpdateList={UpdateList} setIsModalOpen={setIsModalOpen} isModalOpen={isModalOpen} ItemData={ItemData} />}
        </div>
    );
};

export default Cabinet;